﻿using System;
using System.Linq;

namespace Ecobee.Net
{
	public class ThermostatStatusList : ApiObjectCollection<ThermostatStatus>
	{
		protected override void OnLoad(dynamic dataObject)
		{
			foreach (var item in dataObject)
			{
				// ***
				// *** Parse the string into its parts
				// ***
				string[] values = item.ToString().Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

				// ***
				// *** The parsed data will be assigned to a thermostat object
				// ***
				ThermostatStatus thermostatStatus = null;

				// ***
				// *** Check if the thermostat is already in the list
				// ***
				var existingItem = this.Where(t => t.Identifier == values[0]);

				if (existingItem.Count() == 1)
				{
					// ***
					// *** The thermostat already exists.
					// ***
					thermostatStatus = existingItem.Single();
				}
				else
				{
					// ***
					// *** The thermostat does not exist. Create a new object
					// *** and add it to the collection.
					// ***
					thermostatStatus = new ThermostatStatus();
					this.Add(thermostatStatus);
				}

				// ***
				// *** Update the details
				// ***
				thermostatStatus.Identifier = values[0];

				string[] equipmentStatusList = item.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

				foreach (string equipmentStatus in equipmentStatusList)
				{
					EquipmentStatusType status = (EquipmentStatusType)Enum.Parse(typeof(EquipmentStatusType), equipmentStatus);
					thermostatStatus.EquipmentStatus = thermostatStatus.EquipmentStatus | status;
				}
			}
		}
	}
}
